package controller

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"gorm.io/gorm"
	"net/http"
	"strconv"
	"test/common"
	"test/model"
)

func Find_allstudent(ctx *gin.Context) {
	var student []model.Students
	db := common.GetDB()
	result := db.Find(&student)
	fmt.Println(student)
	if result != nil {
		fmt.Println("data")
	}
	ctx.JSON(http.StatusOK,student)
}

func FindStudentByID(ctx *gin.Context) {
	DB := common.GetDB()
	requeststudent := make(map[string]interface{})
	fmt.Println("修该执行")
	var student model.Students
	DB.Last(&student)
	ctx.ShouldBind(&requeststudent)
	ctx.JSON(http.StatusOK,requeststudent)
}

func AddStudent(ctx *gin.Context) {
	DB := common.GetDB()
	requeststudent := make(map[string]interface{})
	//获取参数
	var student model.Students
	DB.Last(&student)
	ctx.ShouldBind(&requeststudent)
	fmt.Println(requeststudent,"我是添加学生")
	sno:=student.Sno + 1
	sname:=requeststudent["Sname"].(string)
	sdate:= requeststudent["Sdate"].(string)
	spassword:=requeststudent["Spassword"].(string)
	spayment,_ := strconv.Atoi(requeststudent["Spayment"].(string))
	//判断该学生是否存在
	if isSnameExists(DB,sname) {
		ctx.JSON(http.StatusUnprocessableEntity,gin.H{"code":422,"msg":"学生已经存在"})
		fmt.Println("我执行了")
		return
	}
	newStudent := model.Students{
		Sno: sno,
		Sname:    sname,
		Sdate: 	  sdate,
		Spayment: spayment,
		Spassword: spassword,
	}
	DB.Create(&newStudent)
	//返回结果
	ctx.JSON(200, gin.H{
		"code" : 200,
		"msg": "添加成功",
	})
}

func isSnameExists(db *gorm.DB,sname string) bool {//string
	var student model.Students
	db.Where("sname = ?",sname).First(&student)
	if student.Sno != 0 {
		return true
	} else {
		return false
	}
}

func DeleteStudent(ctx *gin.Context) {
	DB := common.GetDB()
	fmt.Println("我执行了")
	requeststudent := make(map[string]interface{})
	var students model.Students
	//获取参数
	ctx.ShouldBind(&requeststudent)
	fmt.Println(requeststudent["Sno"].(float64),"我的学号")
	students.Sno = int(requeststudent["Sno"].(float64))
	DB.Where("sno = ?",students.Sno).Delete(&students)
}

func UpdateStudent(ctx *gin.Context)  {
	DB := common.GetDB()
	fmt.Println("我是修该学生信息")
	requestUser := make(map[string]interface{})
	//获取参数
	var students model.Students
	DB.Last(&students)
	ctx.ShouldBind(&requestUser)
	students.Sno = int(requestUser["Sno"].(float64))
	students.Sname=requestUser["Sname"].(string)
	students.Sdate = requestUser["Sdate"].(string)
	students.Spassword =requestUser["Spassword"].(string)
	students.Spayment,_ = strconv.Atoi(requestUser["Spayment"].(string))
	fmt.Println(students)
	DB.Where("sno = ?",students.Sno).Updates(&students)
	ctx.JSON(200, gin.H{
		"code" : 200,
		"msg": "修改成功",
	})
}
